<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/3/11/011
 * Time: 15:07
 */

namespace app\project\controller;


use app\common\controller\Common;
use app\project\service\CommunalService;
use app\project\service\ProjectService;
use think\Controller;
use think\Db;
use think\Exception;
use think\Session;
use think\Validate;

class Communal extends Controller
{
    //拷贝项目
    public function copyApi(){
        try{
            $common = new Common();
            $where['id'] = $_POST['id'];
            $copyDate = $common->public_select("project_pro",$where)->find();
            $copyWhere['library'] = 4;
            $copyWhere['pid'] = empty($copyDate['pid'])?$copyDate['id']:$copyDate['pid'];
            $copyId = $common->public_select("project_pro",$copyWhere)->value('id');
            if(empty($copyId)){
                $copyDate['library'] = 4;
                $copyDate['addtime'] = date("Y-m-d H:i:s");
                $copyDate['add_id'] = Session::get("id");
                $copyDate['pid'] = empty($copyDate['pid'])?$copyDate['id']:$copyDate['pid'];
                unset($copyDate['id']);
                $common->handle("project_pro",$copyDate,1);
            }
            $black['code'] = 0;
            $black['msg'] = "操作成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    //地图搜索
    public function searchApi(){
        $keywork = $_REQUEST['keywork'];
        $url = "https://apis.map.qq.com/ws/place/v1/suggestion/?keyword=".$keywork."&key=Y5IBZ-WT4KU-OLYVW-B77GD-IBUUJ-OFFDZ";
        $black = $this->getSslPage($url);
        $black = json_decode($black);
        return $black;
    }

    function getSslPage($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }


    //发送短信
    public function sendSms()
    {
        try {
            $operation = empty($_POST['operation'])?"":$_POST['operation'];
            $sina = "智慧当阳";
            $pro_id = $_POST['id'];
            //查询项目
            $where['id'] = $pro_id;
            $detail = ProjectService::DetailService($where);
            switch ($operation){
                case "planCareful": //(当阳）完成推进计划审核
                    $code = "SMS_228845034";
                    $duty_person = explode(";",$detail['duty_person']);
                    foreach ($duty_person as $k => $v) {
                        $accountWhere['name'] = $v;
                        $account = ProjectService::AccountService($accountWhere);
                        if (!empty($account['phone'])) {
                            $smsData = [];
                            $smsData['title'] = "【".$detail['title']."】";
                            $smsData['name'] = "【".$v."】";
                            $smsData = json_encode($smsData,JSON_UNESCAPED_UNICODE);
                            $phone = $account['phone'];
                            sms($phone, $sina, $code, $smsData);
                        }
                    }
                    break;
                default:
                    $code = "SMS_228835053";
                    $smsData['name'] = "【".$detail['title']."】";
                    $smsData = json_encode($smsData,JSON_UNESCAPED_UNICODE);
                    foreach ($_POST['getData'] as $k => $v) {
                        $accountWhere['id'] = $v['value'];
                        $account = ProjectService::AccountService($accountWhere);
                        if (!empty($account['phone'])) {
                            $phone = $account['phone'];
                            $blackSms = sms($phone, $sina, $code, $smsData);
                        }
                    }
                    break;
            }

            $black['code'] = 0;
            $black['msg'] = "发送成功";
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    //发送短信
    public function publicSms($phone,$code,$smsData){
        $sina = "智慧当阳";
        sms($phone, $sina, $code, $smsData);
    }

    //重置操作
    public function renderApi(){
        Session::delete("keyword");
          Session::delete("library");
                Session::delete("page");

                Session::delete("duty_unit");
                Session::delete("keyword");
                Session::delete("reply");
                Session::delete("code");
                Session::delete("nature");
                Session::delete("visit_remark");
                Session::delete("project_status");
                Session::delete("warehousing");
                Session::delete("start_status");
                Session::delete("sign");
                Session::delete("duty_person");
                Session::delete("project_type");
                Session::delete("enterprise");
                Session::delete("leader");
                Session::delete("operation");
                Session::delete("condition_val");
                Session::delete("menuTop");
    }

    //添加流程操作
    public function advanceDo(){
        try{
            $common = new Common();
            $CommunalService = new CommunalService();
            $data = $_POST;

            $where['pro_id'] = $data['pro_id'];
            $where['type_id'] = $data['type_id'];
            $where['month'] = $data['month'];
            $where['year'] = $data['year'];
            if(!empty($data['delete'])){
                $id = $common->public_select("project_pro_advance",$where)->delete();
            }else{
                //项目类型,存在判断是否存在
                if(isset($data["sub_id"])){
                    if(empty($data['sub_id'])){
                        throw new Exception("请选择项目类型");
                    }
                    $where['sub_id'] = $data['sub_id'];
                }else{
                    //查询父级
                    $advanceDetail = $CommunalService->advanceDetail(['id'=>$data['type_id']]);
                    $data['sub_id'] = empty($advanceDetail)?0:$advanceDetail['pid'];

                    if(!empty($advanceDetail)){
                        if($advanceDetail['type']==8){
                            $data['plan_category'] = 2;
                        }else{
                            $data['plan_category'] = 1;
                        }
                    }

                }
                $rule = [
                    ["status", "require", "请选择完成情况"],
                    ["content", "require", "计划内容不能为空"],
                ];
                $validate = new Validate($rule);
                if (!$validate->check($data)) {
                    throw new Exception($validate->getError());
                }

                //查询详细信息
                $detail = $CommunalService->proAdvanceDetail($where);

                if(!empty($detail['declare_content']) & $detail['declare_status']==0){
                    if(empty($data['declare_status'])){
                        throw new Exception("请选择审核状态");
                    }
                    $declare_status = $data['declare_status'];

                    if($declare_status==2 & empty($data['declare_remark'])){
                        throw new Exception("请填写备注");
                    }

                    $data['declare_time'] = time();
                    $nowMonth = date("m");
                    $oldMonth = $data['month'];
                    if($nowMonth>$oldMonth){
                        $oldTime = date("Y")."-".$oldMonth."-01";
                        $timeDate = $this->getthemonth($oldTime);
                        $lastday = $timeDate['lastday'];
                        $lastdaytime = strtotime($lastday);
                        $interval = bcsub(time(),$lastdaytime);  //间隔秒数
                        $interval = bcdiv($interval,24*60*60); //间隔天数
                        $data['declare_day'] = $interval;
                    }
                    if($nowMonth==$oldMonth){
                        $timeDate = $this->getNextMonthDays(date("Y-m-d"));
                        $firstday = $timeDate['firstday'];
                        $firstday = strtotime($firstday);
                        $interval = bcsub(time(),$firstday);  //间隔秒数
                        $interval = bcdiv($interval,24*60*60); //间隔天数
                        $data['declare_day'] = $interval;
                    }

                    if($nowMonth<$oldMonth){
                        $oldTime = date("Y")."-".$oldMonth."-01";
                        $timeDate = $this->getthemonth($oldTime);
                        $lastday = $timeDate['firstday'];
                        $lastdaytime = strtotime($lastday);
                        $interval = bcsub(time(),$lastdaytime);  //间隔秒数
                        $interval = bcdiv($interval,24*60*60); //间隔天数
                        $data['declare_day'] = $interval;
                    }
                }
                $CommunalService->advanceDoService($data,$where);
            }

            $black['code'] = 0;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }


    //获取下个月
    function getNextMonthDays($date){
        $timestamp=strtotime($date);
        $arr=getdate($timestamp);
        if($arr['mon'] == 12){
            $year=$arr['year'] +1;
            $month=$arr['mon'] -11;
            $firstday=$year.'-0'.$month.'-01';
            $lastday=date('Y-m-d',strtotime("$firstday +1 month -1 day"));
        }else{
            $firstday=date('Y-m-01',strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)+1).'-01'));
            $lastday=date('Y-m-d',strtotime("$firstday +1 month -1 day"));
        }
        $black['firstday'] = $firstday;
        $black['lastday'] = $lastday;
        return $black;
    }

    //指定月份的第一天与最后一天
    function getthemonth($date)
    {
        $firstday = date('Y-m-01', strtotime($date));
        $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
        $black['firstday'] = $firstday;
        $black['lastday'] = $lastday;
        return $black;
    }


    //推进计划视图(流程天机视图)
    public function addProcedure(){
        $CommunalService = new CommunalService();
        $year = $_GET['year'];
        $procedure = $_GET['procedure'];
        $month = $_GET['month'];
        $thisWechat = Session::get("thisWechat");

        //查询是否存在项目类型
        $where['uniacid'] = $thisWechat['id'];
        $where['status'] = 1;
        $where['pid'] = $procedure;
//        $where['type'] = 5;
        $project_type = $CommunalService->advanceList($where);
        $this->assign("project_type",$project_type);
        //查询详情
        $advanceWhere['year'] = $year;
        $advanceWhere['pro_id'] = $_GET['id'];
        $advanceWhere['type_id'] = $_GET['procedure'];
        $advanceWhere['month'] = $month;
        $detail = $CommunalService->proAdvanceDetail($advanceWhere);

        //图片拆分
        if(!empty($detail['declare_image'])){
            $detail['declare_image'] = explode(",",$detail['declare_image']);
        }
        $this->assign("detail",$detail);
        return view("addProcedure");
    }


    //更新项目计划类别
    public function updatePlan(){
        try{
            $common = new Common();
            $id = $_POST['id'];
            $where['id'] = $id;
            $plan_category = $_POST['plan_id'];
            $update['plan_category'] = $plan_category;
            $common->public_select("project_pro",$where)->update($update);

            $copyWhere['id'] = $id;
            $pid = Db::name("project_pro")->where($copyWhere)->value("pid");

            if(empty($pid)){
                unset($where);
                $where['pid'] = $id;
                $common->public_select("project_pro",$where)->update($update);
            }else{
                unset($where);
                $where['id'] = $pid;
                $common->public_select("project_pro",$where)->update($update);

                unset($where);
                $where['pid'] = $id;
                $common->public_select("project_pro",$where)->update($update);
            }

            $black['code'] = 0;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    //推进计划视图
    public function advanceView(){
        $common = new Common();
        $CommunalService = new CommunalService();
        $id = $_GET['id'];
        $this->assign("id",$id);
        $thisWechat = Session::get("thisWechat");
        //查询当前年份
        $year = empty($_GET['year'])?date("Y"):$_GET['year'];
        $arr = [1,2,3,4,5,6,7,8,9,10,11,12];
        $month = [];
        foreach ($arr as $k=>$v){
            $month[$k]['name'] = $v;
            $month[$k]['status'] = 0;
        }
        $this->assign("month",$month);
        //查询项目
        $detail = $CommunalService->findDetail($id);
        $this->assign("detail",$detail);

        $selType = 0;

        $library = $detail['library'];

        if($detail['plan_category'] == 1){
            $selType = 7;
        }
        if($detail['plan_category'] == 2){
            $selType = 8;
        }

        $project_type = $CommunalService->projectTypeService($thisWechat,$selType,$id,$year,$month,$library);
        $this->assign("project_type",$project_type);

        //计划类别
        $plan_category = [
            1=>"政府投资",
            2=>"社会投资"
        ];
        $this->assign("detail",$detail);
        $this->assign("plan_category",$plan_category);
        $this->assign("year",$year);
        return view("advanceView");
    }


    //快捷操作
    public function clickStatus(){
        try{
            $data['is_score'] = $_POST['status'];
            $table = empty($_POST['table'])?"project_account":$_POST['table'];
            Db::name($table)->where(['id' => $_POST['id']])->update($data);

            $black['code'] = 0;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    //批量操作视图
    public function batchView(){

        if(!empty($_POST)){
           try{
               $id = $_POST['id'];
               $id = explode(",",$id);
               $where['id'] = ['in',$id];
               $data['invest_type'] = $_POST['invest_type'];
               Db::name("project_pro")->where($where)->update($data);
               $black['code'] = 0;
               $black['msg'] = "操作成功";
           }catch (Exception $e){
               $black['code'] = 202;
               $black['msg'] = $e->getMessage();
           }
            return $black;
        }

        return view("batchView");
    }


    //查询企业类型
    public function selType(){
        try{
            $where['menuTop'] = $_POST['menuTop'];
            if(!empty($_POST['menuTop'])){
//                $where['menuTop'] = ['in',[1,2]];
                $where['status'] = 1;
                $list = Db::name("project_type")->where($where)->select();
            }

            $black['code'] = 0;
            $black['list'] = $list??[];
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    //查询二级分类
    public function twoListApi(){
        try{
            $where['pid'] = $_POST['menuTop'];
            $where['status'] = 1;
            $list = Db::name("project_type")->where($where)->select();
            $black['code'] = 0;
            $black['list'] = $list;
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }


    /**
     * 数据字典，查询字典
     * @param $keword
     * @return mixed
     */
    public function dictionary($keword=0,$type=0){
        $thisWechat = Session::get("thisWechat");
        $where['uniacid'] = $thisWechat['id'];
        $where['status'] = 1;
        if(!empty($type)){
            $where['type'] = $type;
        }

        $black = Db::name($keword)->where($where)->field("id,name")->select();
        $data = [];
        foreach ($black as $k=>$v){
            $data[] = ['value'=>$v['id'],'title'=>$v['name']];
        }
        return $data;
    }

    //选择项目视图
    public function projectlist()
    {
        $id = $_POST['id'];
        $this->assign('id',$id);
        return view("projectlist");
    }

    //获取项目列表
    public function projectlists()
    {
        $page = empty($_GET['page']) ? 1 : $_GET['page'];
        $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
        $start = ($page - 1) * $limit;
        $where = [];
        if (!empty($_GET['keyword1'])) {
            $where['title'] = ['like', "%" . $_GET['keyword1'] . "%"];
        }

        if (!empty($_GET['sign'])) {
            $where['sign'] = $_GET['sign'];
        }

        $thisWechat = Session::get("thisWechat");
        $where['uniacid'] = $thisWechat['id'];
        //查询一关联项目
        $pro = Db::name("project_account_pro")->where(['account_id'=>$_GET['account_id']])->field("project_id")->select();
        $pro_k = [];
        foreach ($pro as $v){
            $pro_k[] = $v['project_id'];
        }
        if (!empty($_GET['associated'])) {
            $associated = $_GET['associated'];
            if($associated==2){
                $where['id'] = ['in',$pro_k];
            }else{
                $where['id'] = ['not in',$pro_k];
            }
        }
        if (!empty($_GET['library'])) {
            $library = $_GET['library'];
            $where['library'] = $library;
        }
//        if(!empty($pro_k)){
//            $where['id'] = ['not in',$pro_k];
//        }
        //查询所有项目
        $data = Db::name("project_pro")->field("id,title,investment,onstream_time")->limit($start, $limit)->where($where)->order("id desc")->select();

        foreach ($data as $k=>$v){
            $data[$k]['hasbeen'] = in_array($v['id'],$pro_k)?1:0;
        }

        $count = Db::name("project_pro")->field("id,propertyName")->where($where)->count("id");
        $black['code'] = 0;
        $black['count'] = $count;
        $black['data'] = $data;
        return $black;
    }

}